import React, { useContext, FunctionComponentElement, useState } from 'react';
import classNames from 'classnames';
import { CSSTransition } from 'react-transition-group';

import { MenuContext } from './menu';
import { MenuItemProps } from './menuItem';
import Icon from '../Icon/icon';
import Transition from '../Transition/transition';

export interface SubMenuProps {
  index?: string;
  title: string;
  className?: string;
}

const SubMenu: React.FC<SubMenuProps> = ({ index, title, children, className }) => {
  const context = useContext(MenuContext);
  const openedSubMenus = context.defaultOpenSubMenus as Array<String>;
  const isOpend = (index && context.mode === 'vertical') ? openedSubMenus.includes(index) : false ;
  const [menuOpen, setOpen] = useState(isOpend);

  // 类名
  const classes = classNames('origin-menu-item origin-submenu-item', {
    "origin-menu-is-active": context.index[0] === index
  });

  // 点击隐藏
  const handleClick = (e: React.MouseEvent) => {
    e.preventDefault();
    setOpen(!menuOpen);
    activeHandleClick()
  }

  let timer: any;
  // 'horizontal 划过显示
  const handleMouse = (e: React.MouseEvent, toggle: boolean) => {
    clearTimeout(timer);
    e.preventDefault();
    timer = setTimeout(() => {
      setOpen(toggle);
    }, 300);
  }
  
  // 划过执行
  const hoverEvents = context.mode !== 'vertical' ? {
    onMouseEnter: (e: React.MouseEvent) => { handleMouse(e, true) },
    onMouseLeave: (e: React.MouseEvent) => { handleMouse(e, false) }
  } : {};

  // 点击事件
  const clickEvents = context.mode === 'vertical' ? {
    onClick: handleClick
  } : "";

  const renderChildren = () => {
    const subMenuClasses = classNames('origin-submenu', {
      'menu-opened': menuOpen
    })
    const childrenComponent = React.Children.map(children, (child, i) => {
      const childElement = child as FunctionComponentElement<MenuItemProps>
      if (childElement.type.displayName === 'MenuItem') {
        return React.cloneElement(childElement, {
          index: `${index}-${i}`
        });
      } else {
        console.log("Warning: SubMenu has a child which is not a MenuItem");
      }
    })
    return (
      <Transition
        in={menuOpen}
        timeout={300}
        animation="zoom-in-top"
      >
        <ul className={ subMenuClasses }>
          {childrenComponent}
        </ul>
      </Transition>
    )
  }
  // 当前高亮
  const activeHandleClick = () => {
    if (context.onSelect && (typeof index === 'string') ) {
      context.onSelect(index);
    }
  }

  return (
    <li key={index} className={classes} {...hoverEvents}>
      <div className="submenu-title" {...clickEvents}>
        {title}
        <Icon icon="angle-down" className="origin-arrow-icon"></Icon>
      </div>
      { renderChildren() }
    </li>
  )
}

SubMenu.displayName = 'SubMenu';

export default SubMenu;